<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>五角星评分案例-jQuery</title>
  <style>
    span {
      display: inline-block;
      width: 80px;
    }

    span.pj {
      cursor: pointer;
      font-size: 20px;
      width: 30px;
      text-align: center;
    }

    div {
      line-height: 40px;
      text-align: center
    }

    .enabled {
      color: red;
    }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script>
    $(document).ready(function () {
      // 每一个div的className
      var divClassName = ["zongti", "kouwei", "huanjing", "fuwu"];
      // 每一个div下的第一个span里面的文字
      var firstSpanText = ["总体评价:", "口味评价:", "环境评价:", "服务评价:"];
      // 设置星星的个数
      var starNumber = 5;


      // 调用createDiv函数
      createDiv(divClassName, firstSpanText);
      // 调用diaoyongjiaxing函数
      diaoyongjiaxing(divClassName, ".pj", "enabled");




      // 声明一个函数用来创建div和带有文字的span,个数有divClassName数组的长度决定
      function createDiv(divClassName, firstSpanText) {
        for (let i = 0; i < divClassName.length; i++) {
          // 创建div
          var div = "<div class=" + divClassName[i] + "></div>";
          $("body").append(div);
          // 创建带有文字的span
          var span = "<span>" + firstSpanText[i] + "</span>";
          $("." + divClassName[i]).append(span); //设置星星个数，和类名，插入到第几个组中
          // 调用函数createSpanStart，创建带有星星的span
          createSpanStar(starNumber, "pj", i);
        }
      };

      // 声明一个函数用来创建带星星的span
      function createSpanStar(starNumber, className, i) {
        for (let j = 0; j < starNumber + 1; j++) {
          var span = "<span class=" + className + ">★</span>"
          $("." + divClassName[i]).append(span);
        }
      };

      // 声明diaoyongjiaxing函数用来调用jiaxing函数
      function diaoyongjiaxing(divClassName, spanClassName, className) {
        for (let index = 0; index < divClassName.length; index++) {
          jiaxing($("." + divClassName[index] + " " + spanClassName), className);
        }
      };

      //声明jiaxing函数，给星星上色
      function jiaxing(element, className) {
        $(element).click(function (e) {
          e.preventDefault();
          // 0.初始化，把所有的星号的颜色去除
          $(element).removeClass(className)
          // 1.得到单机星星的序号
          let num = $(element).index(this);
          console.log(num);
          for (let i = 0; i <= num; i++) {
            $(element).eq(i).addClass(className);
          }
        });
      };
    });
  </script>
</head>

<body>
</body>

</html>